package cn.com.gsoft.proxy;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class for Servlet: SSORedirect
 *
 */
 public class SSORedirect extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public SSORedirect() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}  	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try
		{
			
			PrintWriter pw = response.getWriter();
			
			String ltpaToken = (String)request.getParameter("LtpaToken");
			String targetURL = (String)request.getParameter("RedirectTo");
			char ch = 32;
			ltpaToken = ltpaToken.replace(ch, '+');
			Config config = new Config();
			String domain = config.getAttribute("SSODOMAIN");
			Cookie cookie = new Cookie("LtpaToken", ltpaToken);
			cookie.setPath("/");
			cookie.setDomain(domain);
			response.addCookie(cookie);
			
			if(targetURL == null)
			{
				pw.print("<script>document.location='/names.nsf';</script>");
			}else
			{
				pw.print("<script>document.location='" + targetURL + "';</script>");
			}
		
			
		}catch(Exception ex)
		{
			ex.printStackTrace();
		}			
	}
	
	public String readValue(String key) {
		  Properties props = new Properties();
		  try {
			  InputStream in = new BufferedInputStream (new FileInputStream("resources/application.properties"));
			  props.load(in);
			  String value = props.getProperty (key);
			  return value;
		  } catch (Exception e) {
			  e.printStackTrace();
			  return null;
		  }
	}

}